//
//  CTShare.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/5/12.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTShare.h"
#import "WXApi.h"
#import "WXApiObject.h"
#import "AppDelegate.h"
#import "CTDebugManager.h"
#import "CTImageProcessing.h"
#import "CTReachability.h"
#import <ShareSDK/ShareSDK.h>
#import "CTShareItem.h"
#import "CTImageProcessing.h"
#import "CTRemindView.h"
#import "CTAppLanguage.h"
#import "CTFile.h"
#import "CTTextManager.h"

#import <TencentOpenAPI/QQApi.h>



@implementation CTShare



+(void)shareItem:(CTShareItem *)item
    shareChannel:(CTShareChannel)shareChannel
     publishType:(CTPublishType)pubtype
shareSuccessHandler:(CTShareSuccessedBlock)successBlock
shareFailedHandler:(CTShareFailedBlock)failedBlock
{
    /* 检查网络 */
    
   if ((CTNetWorkReachabilityStatus)[CTReachability judegeCurrentNetWorkStatus] == CTNetWorkReachabilityStatusNotReachable) {
       CTRemindView * remindView = [[CTRemindView alloc] init];
       [remindView showRemindViewWithRemindWord:[CTAppLanguage localizedStringForKey:@"remindview_share_a" withValue:nil withTable:@"Language"]];
        return;
    }
    
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    
    
    SSPublishContentMediaType publishContentMediaType;
    
    switch (pubtype) {
        case CTPublishTypeImage:
            publishContentMediaType = SSPublishContentMediaTypeImage;
            break;
        case CTPublishTypeText:
            publishContentMediaType = SSPublishContentMediaTypeText;
            break;
        case CTPublishTypeNews:
            publishContentMediaType = SSPublishContentMediaTypeNews;
            break;
        default:
            break;
    }
    
    
    ShareType shareType;
    
    switch (shareChannel) {
        case CTShareChannelFaceBook:
            shareType = ShareTypeFacebook;
            break;
        case CTShareChannelInstagram:
            shareType = ShareTypeInstagram;
            break;
        case CTShareChannelQQ:
            shareType = ShareTypeQQ;
            break;
        case CTShareChannelQQSpace:
            shareType = ShareTypeQQSpace;
            break;
        case CTShareChannelSina:
            shareType = ShareTypeSinaWeibo;
            break;
        case CTShareChannelLine:
            shareType = ShareTypeLine;
            break;
        case CTShareChannelTwitter:
            shareType = ShareTypeTwitter;
            break;
        case CTShareChannelWechat:
            //微信
            shareType = ShareTypeWeixiSession;
//            [self wechatShare:item];
//            successBlock();
//            return;
            break;
        case CTShareChannelWechatFriend:
            shareType = ShareTypeWeixiTimeline;
            break;
        case CTShareChannelWhatsapp:
            shareType = ShareTypeWhatsApp;
            break;
        case CTShareChannelMessage:
            
            break;
        case CTShareChannelEmail:
            shareType = ShareTypeMail;
            break;
            
        default:
            break;
    }
   
    //创建分享内容
    id<ISSContent> publishContent = [ShareSDK content:item.content
                                       defaultContent:item.defaultContent
                                                image:[ShareSDK pngImageWithImage:item.img]
                                                title:item.title
                                                  url:item.url
                                          description:item.descr
                                            mediaType:publishContentMediaType];
//    NSLog(@"item.content %@\n item.defaultContent%@\n item.img %@\n item.title%@\n item.url%@\n item.descr%@\n",item.content,item.defaultContent,item.img,item.title,item.url,item.descr);
    
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:YES
                                                         authViewStyle:SSAuthViewStyleFullScreenPopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:appDelegate.agViewDelegate];
    
    //    //在授权页面中添加关注官方微博
    [authOptions setFollowAccounts:[NSDictionary dictionaryWithObjectsAndKeys:
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeSinaWeibo),
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeTencentWeibo),
                                    nil]];
    
    
    //显示分享菜单
    [ShareSDK showShareViewWithType:shareType
                          container:nil
                            content:publishContent
                      statusBarTips:YES
                        authOptions:authOptions
                       shareOptions:[ShareSDK defaultShareOptionsWithTitle:nil
                                                           oneKeyShareList:[NSArray defaultOneKeyShareList]
                                                            qqButtonHidden:NO
                                                     wxSessionButtonHidden:NO
                                                    wxTimelineButtonHidden:NO
                                                      showKeyboardOnAppear:NO
                                                         shareViewDelegate:appDelegate.agViewDelegate
                                                       friendsViewDelegate:appDelegate.agViewDelegate
                                                     picViewerViewDelegate:nil]
                             result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                 
                                 if (state == SSPublishContentStateSuccess)
                                 {
                                     successBlock();
                                     [CTDebugManager showDebugLogInfo:@"分享成功"];
                                 }
                                 else if (state == SSPublishContentStateFail)
                                 {
                                     switch (shareChannel) {
                                         case CTShareChannelQQ:
                                         case CTShareChannelQQSpace:
                                         {
                                             
                                             if ([QQApi isQQInstalled])
                                             {
                                                 failedBlock();
                                             }
                                             else
                                             {
                                                 UIAlertView * shareAlertView = [[UIAlertView alloc]initWithTitle:@"提醒" message:@"没有安装QQ或QQ版本过低" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                                                 [shareAlertView show];
                                             }
                                         }
                                             break;
                                         case CTShareChannelWechat:
                                         case CTShareChannelWechatFriend:
                                         {
                                             if ([WXApi isWXAppInstalled])
                                             {
                                                 failedBlock();
                                             }
                                             else
                                             {
                                                 UIAlertView * shareAlertView = [[UIAlertView alloc]initWithTitle:@"提醒" message:@"没有安装微信或微信版本过低" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                                                 [shareAlertView show];
                                             }
                                         }
                                             break;
                                             
                                         default:
                                             break;
                                     }
                                     
                                     
                                     
                                     
                                     
                                     [CTDebugManager showErrorLogInfo:@"分享失败"];
                                 }
                             }];
    
}


+(void)wechatShare:(id)itm
{
    CTShareItem * item = (CTShareItem *)itm;
    
    
    WXMediaMessage *message = [WXMediaMessage message];
    UIImage *image = [CTImageProcessing imageCompressionImg:item.img WithSize:CGSizeMake(320, 320)];
    [message setThumbImage:image];
    WXEmoticonObject *ext = [WXEmoticonObject object];
    ext.emoticonData = UIImageJPEGRepresentation(item.img, 0);
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneSession;
    
    [WXApi sendReq:req];
}









+ (BOOL)isSinaShare
{
   NSString * isShareStr =  [CTFile getFile:@"share.text" fromDoc:CTFileDocLibrary fromPath:@"cacheData/publish/share"];
    
    if ([[CTTextManager shareInstance] isBlankString:isShareStr] == YES) {
        return NO;
    }else{
        if ([isShareStr isEqualToString:@"1"]) {
            return YES;
        }else{
            return NO;
        }
    }
}

+ (void)setSinaShare:(BOOL)share
{
    if (share == YES) {
        [CTFile cacheFile:@"1" fileName:@"share.text" saveDoc:CTFileDocLibrary savePath:@"cacheData/publish/share"];
    }else{
        [CTFile cacheFile:@"0" fileName:@"share.text" saveDoc:CTFileDocLibrary savePath:@"cacheData/publish/share"];
    }
}


+ (void)sinaBtnAction:(CTShareItem *)itm shareSuccessHandler:(CTShareSuccessedBlock)successBlock shareFailedHandler:(CTShareFailedBlock)failedBlock
{

    CTShareItem * item = (CTShareItem *)itm;
//    NSLog(@"item.content %@\n item.defaultContent%@\n item.img %@\n item.title%@\n item.url%@\n item.descr%@\n",item.content,item.defaultContent,item.img,item.title,item.url,item.descr);

    id<ISSContent> publishContent = [ShareSDK content:item.content
                                       defaultContent:item.defaultContent
                                                image:[ShareSDK pngImageWithImage:item.img]
                                                title:item.title
                                                  url:item.url
                                          description:item.descr
                                            mediaType:SSPublishContentMediaTypeText];
    [ShareSDK shareContent:publishContent
                      type:ShareTypeSinaWeibo
               authOptions:nil
             statusBarTips:YES
                    result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                        
                        if (state == SSPublishContentStateSuccess)
                        {
                            [CTDebugManager showDebugLogInfo:@"发表成功"];
                            [CTDebugManager showDebugLogInfo:@"分享成功"];

                            successBlock();
                        }
                        else if (state == SSPublishContentStateFail)
                        {
                            [CTDebugManager showErrorLogInfo:[NSString stringWithFormat:@"发布失败!error code == %ld, error code == %@", (long)[error errorCode], [error errorDescription]]];
                            
                            failedBlock();
                        }
                    }];
    
}

@end
